package com.seekting.mynews.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;

import com.seekting.mynews.App;
import com.seekting.mynews.connect.tiangou.bean.offline.TianGou;
import com.seekting.mynews.eventbus.TianGouClassifyEvent;
import com.seekting.mynews.manager.Action;
import com.seekting.mynews.manager.NewsManager;

import cn.trinea.android.common.util.NetWorkUtils;
import de.greenrobot.event.EventBus;

/**
 * Created by seekting on 2016/2/2.
 */
public class OffLineService extends Service {
    private static final int MSG_BEGIN = 1;
    TianGou tianGou;

    Handler handler;
    private NewsManager newsManager;
    private String currentRequest;
    private boolean downloading = false;

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        newsManager = App.getApp().getManager(NewsManager.class);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                OffLineService.this.handleMessage(msg);
            }
        };
    }

    public void onEventMainThread(TianGouClassifyEvent tianGouClassifyEvent) {
        if (TextUtils.isEmpty(currentRequest)) {
            return;
        }
        if (currentRequest.equals(tianGouClassifyEvent.getTianGouClassify().getUuid())) {
            tianGou.setTianGouClassify(tianGouClassifyEvent.getTianGouClassify());
        }

    }

    private void setDownloading(boolean downloading) {
        this.downloading = downloading;
    }

    public void handleMessage(Message msg) {

        switch (msg.what) {
        case MSG_BEGIN:
            downloading = true;
            String netWorkName = NetWorkUtils.getNetworkTypeName(this);
            if (NetWorkUtils.NETWORK_TYPE_WIFI.equals(netWorkName)) {

                return;
            }
            currentRequest = newsManager.request(Action.TianGouClassify, new Bundle());
            break;

        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        handler.sendEmptyMessageDelayed(MSG_BEGIN, 3000);
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
